import { AudioClip, AudioSource, Component, resources, _decorator } from 'cc';
const { ccclass } = _decorator;

@ccclass('SingleAudio')
export class SingleAudio extends Component {
  // 音频资源路径
  private audioClipPath: string = 'Sound/coin'; // 不需要加扩展名

  // AudioSource 组件
  private audioSource: AudioSource | null = null;

  private audioClip: AudioClip = null;

  onLoad() {
    this.scheduleOnce(this.playThreeTimes, 3);
  }

  playThreeTimes() {
    const onPlayEnd = (index: number) => {
      // console.log('播放结束', index);
    };
    // 连续播放三次
    for (let i = 0; i < 3; i++) {
      this.scheduleOnce(() => {
        this.play('32_1', false, () => {
          onPlayEnd(i);
        });
      }, i * 1); // 每次播放间隔 0.5 秒
    }
  }

  play = (audioClipPath: string, loop: boolean, callback?: () => void) => {
    if (!this.audioClip) {
      // 需要预加载音频资源
      resources.load(audioClipPath, AudioClip, (err, clip) => {
        if (err) {
          console.error('Failed to load audio clip:', audioClipPath, err);
        } else {
          // console.log('Audio clip loaded:', audioClipPath);
          // 创建 AudioSource 组件
          if (!this.audioSource) {
            this.audioSource = this.node.addComponent(AudioSource);
          }
          this.audioClip = clip;
          this.audioSource.clip = clip;
          this.audioSource!.play();
          if (callback) {
            this.audioSource.scheduleOnce(callback, this.audioSource.duration);
          }
        }
      });
    } else {
      this.audioSource!.play();
      if (callback) {
        this.audioSource.scheduleOnce(callback, this.audioSource.duration);
      }
    }
  };
}
